package com.字符串判空;


import java.util.Optional;

/**
 * @author Administrator
 * @date 2021/9/19
 * @description: 一个User类定义
 */


public class User {
    private String name;

    private String gender;
    private School school;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public School getSchool() {
        return school;
    }

    public void setSchool(School school) {
        this.school = school;
    }

    /**
     * 
     * @param user
     * @return
     * @throws Exception
     * 
     *         案例一
     */
    public String getCity(User user) throws Exception {

        // 以前的写法

        // if (user != null) {
        // if (user.getSchool() != null) {
        // School school = user.getSchool();
        // if (school != null) {
        // return school.getAddress();
        // }
        // }
        // }
        // throw new Exception("取值错误");

        // java8 写法

        return Optional.ofNullable(user).map(User::getSchool).map(School::getAddress)
                        .orElseThrow(() -> new Exception("取值错误"));

    }

    /**
     * 
     * @param user
     * 
     *        案例二
     */

    public void getXX(User user) {
        // 以前的写法
        if (user != null) {
            doSomeThing(user);
        }

        // java8 写法
        // ifPresent() 函数，当value值不为空时，执行函数体
        Optional.ofNullable(user).ifPresent(t -> {
            doSomeThing(user);
        });
    }

    private void doSomeThing(User user) {}


    /**
     * 
     * @param user
     * @return
     * 
     * 
     *         案例三
     */

    public User getUser(User user) {
        // 以前的写法
        // if (user != null) {
        // String name = user.getName();
        // if ("zhang".equals(name)) {
        // return user;
        // }
        // } else {
        // user = new User();
        // user.setName("zhang");
        // return user;
        // }
        // return null;


        // java8 写法
        // orElseGet() 函数，当user不为null时，不会执行括号中的匿名方法体

        return Optional.ofNullable(user).filter(t -> "zhang".equals(t.getName())).orElseGet(() -> {
            User user1 = new User();
            user1.setName("zhang");
            return user1;
        });
    }

}




class School {
    private String scName;
    private String address;

    public String getScName() {
        return scName;
    }

    public void setScName(String scName) {
        this.scName = scName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
